package com.server.llh.llhserverwork.activity.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseActivity;
import com.server.llh.llhserverwork.activity.my.PayTaskActivity;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.SerTransField;
import com.server.llh.llhserverwork.bean.SerTransWapBean;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.TimeUtils;
import com.server.llh.llhserverwork.utils.ToastTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by ZTF on 2017-06-06.
 */

public class HealthTaskActivity extends LlhBaseActivity {
    private static final String TAG = " HealthTask";
    @BindView(R.id.startTime)
    TextView startTime;
    @BindView(R.id.stopTime)
    TextView stopTime;
    @BindView(R.id.queryServer)
    TextView queryServer;
    @BindView(R.id.timeView)
    LinearLayout timeView;
    @BindView(R.id.health_lv)
    ListView healthLv;
    String userId, orgId, orgType, userNameStr, serSignRecordId,
            supplierName, token;
    String transStatus, signCustomerId;
    public static final int SEARCH_TYPE = 1;
    SwipeRefreshLayout swipeContainer;
    private List<SerTransField> fieldList = new ArrayList<SerTransField>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        swipeContainer = (SwipeRefreshLayout) this.findViewById(R.id.swipe_container);
        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        token = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR,
                getApplicationContext());
        userNameStr = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_NAMW,
                getApplicationContext());
        serSignRecordId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.SINGN_ID,
                getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        orgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        signCustomerId = SharedPreferenceUtil.getUserInfo(
                Constants.UserInfo.SIGN_CUSTOMER_ID, getApplicationContext());
        Intent intent = getIntent();
        if (intent != null) {
            transStatus = intent.getStringExtra("transStatus");
        }
        try {
            getServerTask(userId, signCustomerId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    getServerTask(userId, signCustomerId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void getServerTask(String userId, String signCustomerId) throws JSONException {
        try {
            JSONObject json = new JSONObject();
            json.put("waitersId", userId);
            json.put("transStatus", transStatus);
            json.put("searchType", SEARCH_TYPE);
            signCustomerId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.SIGN_CUSTOMER_ID,
                    getApplicationContext());
            if (!TextUtils.isEmpty(signCustomerId) && !"".equals(signCustomerId)) {
                json.put("customerId", signCustomerId);
            }
            LRequest lRequest = new LRequest();
            lRequest.addParam("token", token);
            lRequest.addParam("searchTaskForWaitersForApp", URLEncoder.encode(json.toString(), "UTF-8"));
            lRequest.setUri(ServerPort.SEARCH_TASK_JSON);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null) {
//                        listData.clear();
                        Log.d(TAG, "responseBean==" + responseBean);
                        listData = new Gson().fromJson(responseBean,
                                new TypeToken<List<SerTransWapBean>>() {
                                }.getType());
                        adapter = new HealthTaskAdapter(
                                getApplicationContext(), listData);
                        healthLv.setAdapter(adapter);
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    HealthTaskAdapter adapter = null;
    List<SerTransWapBean> listData = new ArrayList<>();

    public class HealthTaskAdapter extends BaseAdapter {

        private int mLastVisibility;
        private int mLastPosition;
        private View mLastView;
        List<SerTransWapBean> listData;

        public List<SerTransWapBean> getListData() {
            return listData;
        }

        public void setListData(List<SerTransWapBean> listData) {
            this.listData = listData;
        }

        private Context context;

        public HealthTaskAdapter(Context context, List<SerTransWapBean> listData) {
            this.listData = listData;
            this.context = context;
            mLastPosition = -1;
        }

        @Override
        public int getCount() {
            return listData == null ? 0 : listData.size();
        }

        @Override
        public Object getItem(int arg0) {
            return listData == null ? null : listData.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            ViewHolder holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.subscribe_item_view, null);
                holder.server_name = (TextView) convertView
                        .findViewById(R.id.client_name);
                holder.client_age = (TextView) convertView
                        .findViewById(R.id.client_age);
                holder.server_time = (TextView) convertView
                        .findViewById(R.id.server_time);
                holder.order_time = (TextView) convertView
                        .findViewById(R.id.order_time);
                holder.client_num = (TextView) convertView
                        .findViewById(R.id.client_num);
                holder.client_server = (TextView) convertView
                        .findViewById(R.id.client_server);
                holder.subscribe_server_order = (TextView) convertView
                        .findViewById(R.id.subscribe_server_order);
                holder.subscribe_Revoke = (TextView) convertView
                        .findViewById(R.id.subscribe_Revoke);
                holder.client_address = (TextView) convertView
                        .findViewById(R.id.client_address);
                holder.content_view = (ListView) convertView
                        .findViewById(R.id.content_view);
                holder.textcreate = (TextView) convertView
                        .findViewById(R.id.textcreate);
                holder.server_remark = (TextView) convertView
                        .findViewById(R.id.server_remark);
                holder.ll_value = (LinearLayout) convertView
                        .findViewById(R.id.ll_value);
                HealthValueAdapter otherAdapter = new HealthValueAdapter();
                holder.content_view.setAdapter(otherAdapter);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final SerTransWapBean taskBean = listData.get(position);
            taskBean.setPosition(position);
            HealthValueAdapter otherAdapter = null;

            if (holder.content_view.getAdapter() != null) {
                otherAdapter = (HealthValueAdapter) holder.content_view
                        .getAdapter();
            } else {
                otherAdapter = new HealthValueAdapter();
            }
            otherAdapter.setSerTransField(taskBean.getFieldList());
            otherAdapter.notifyDataSetChanged();

            if ("5".equals(taskBean.getTransStatus())
                    || "4".equals(taskBean.getTransStatus())) {
                holder.subscribe_server_order.setText("执行任务");
            } else {
                holder.subscribe_server_order.setVisibility(View.VISIBLE);
            }
            holder.subscribe_server_order
                    .setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Long a = taskBean.getSubCateId();

                            int isHasField = taskBean.getIsHasField();

                            if (isHasField == 1) {
                                if ("2".equals(SharedPreferenceUtil
                                        .getUserInfo(Constants.UserInfo.SIGN_STATUS,
                                                getApplicationContext()))) {
                                    ToastTool.showText(
                                            getApplicationContext(),
                                            "请签到,谢谢");
                                    return;
                                }
                                View view = (View) v.getParent()
                                        .getParent();
                                changeImageVisable(view,
                                        taskBean.getPosition());
                            } else {
                                if ("2".equals(SharedPreferenceUtil
                                        .getUserInfo(Constants.UserInfo.SIGN_STATUS,
                                                getApplicationContext()))) {
                                    ToastTool.showText(
                                            getApplicationContext(),
                                            "请签到,谢谢");
                                    return;
                                } else if (taskBean.getSubCateId() != null && a == 1) {
                                    Intent intent = new Intent(
                                            getApplicationContext(),
                                            PayTaskActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.putExtra("serTransId",
                                            taskBean.getSerTransId() + "");
                                    intent.putExtra("transStatus",
                                            taskBean.getTransStatus() + "");
                                    intent.putExtra("subCateId",
                                            taskBean.getSubCateId() + "");
                                    intent.putExtra("customerId",
                                            taskBean.getCustomerId() + "");
                                    intent.putExtra("supplierTypeId",
                                            taskBean.getSupplierTypeId());
                                    intent.putExtra("supplierId",
                                            taskBean.getSupplierId());
                                    startActivity(intent);
                                } else {
                                    long serTransId = taskBean
                                            .getSerTransId();
                                    try {
                                        uploadReSend(serTransId, "6", position);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        }
                    });
            holder.subscribe_Revoke.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    long serTransId = taskBean.getSerTransId();
                    try {
                        uploadReSend(serTransId, "9", position);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            holder.order_time.setText(TimeUtils.dateToString(taskBean
                    .getAddTime()));
            holder.server_name.setText(taskBean.getCustomerName());
            holder.client_age.setText("");
            // holder.client_address.setVisibility(View.GONE);
            // holder.client_address.setText("￥ " + taskBean.getPrice() + " 元");
                holder.client_server.setText("电话:"+taskBean.getCustomerPhone());
            holder.client_address.setText("" + taskBean.getServiceName());
            holder.client_num.setText(taskBean.getCustomerPhone());
            String startTime = TimeUtils.dateToString(taskBean
                    .getSerStartTime());
            String endTimeStr = TimeUtils
                    .dateToString(taskBean.getSerEndTime());
            holder.server_time.setText(startTime.substring(5,
                    startTime.length() - 3)
                    + "--" + endTimeStr.substring(5, endTimeStr.length() - 3));

            holder.textcreate.setTag(holder.content_view);
            holder.textcreate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ListView listView = (ListView) v.getTag();
                    View temp = null;
                    StringBuffer sb = new StringBuffer();
                    SerTransField data = null;
                    StringBuffer fieldId = new StringBuffer();
                    StringBuffer fieldName = new StringBuffer();
                    ArrayList<Integer> prositonList = new ArrayList<Integer>();
                    for (int i = 0; i < listView.getChildCount(); i++) {
                        SerTransField transField = new SerTransField();
                        transField.setSerTransFieldId(taskBean.getFieldList()
                                .get(i).getSerTransFieldId());
                        temp = listView.getChildAt(i).findViewById(
                                R.id.et_values);
                        if (temp != null) {
                            EditText ed = (EditText) temp;
                            data = (SerTransField) temp.getTag();
                            prositonList.add(data.getPosition());
                            sb.append(ed.getText().toString()).append(",");
                            fieldId.append(data.getFieldId()).append(",");
                            fieldName.append(data.getFieldName()).append(",");
                            transField.setFieldValue(ed.getText().toString());
                            ed.setText("");
                        }
                        if (temp.getClass() == RelativeLayout.class) {
                            temp = temp.findViewById(R.id.et_values);
                        }
                        fieldList.add(transField);

                    }
                    long serTransId = taskBean.getSerTransId();
                    try {
                        uploadReSendValue(serTransId, "6", position);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            if (mLastPosition == position) {
                holder.ll_value.setVisibility(mLastVisibility);
            } else {
                holder.ll_value.setVisibility(View.GONE);
            }

            return convertView;
        }

        public void changeImageVisable(View view, int position) {
            if (mLastView != null && mLastPosition != position) {
                ViewHolder holder = (ViewHolder) mLastView.getTag();
                switch (holder.ll_value.getVisibility()) {
                    case View.VISIBLE:
                        holder.ll_value.setVisibility(View.GONE);
                        mLastVisibility = View.GONE;
                        notifyDataSetChanged();
                        HealthValueAdapter otherAdapter = new HealthValueAdapter();
                        otherAdapter.notifyDataSetChanged();
                        break;
                }
            }
            mLastPosition = position;
            mLastView = view;
            ViewHolder holder = (ViewHolder) view.getTag();
            switch (holder.ll_value.getVisibility()) {
                case View.GONE:
                    holder.ll_value.setVisibility(View.VISIBLE);
                    mLastVisibility = View.VISIBLE;
                    notifyDataSetChanged();
                    HealthValueAdapter otherAdapter = new HealthValueAdapter();
                    otherAdapter.notifyDataSetChanged();
                    break;
                case View.VISIBLE:
                    holder.ll_value.setVisibility(View.GONE);
                    mLastVisibility = View.GONE;
                    notifyDataSetChanged();
                    HealthValueAdapter otherAdapter1 = new HealthValueAdapter();
                    otherAdapter1.notifyDataSetChanged();
                    break;
            }
        }

        class ViewHolder {
            TextView te_name, server_name, server_time, server_finish, order_time,
                    client_server, client_age, client_address, client_num,
                    subscribe_Revoke, subscribe_server_order, server_remark,textcreate,
                    client_server_time, unitName;
            ImageView llh_image;
            ListView content_view;
            LinearLayout ll_value;

            EditText te_values;
        }

        class HealthValueAdapter extends BaseAdapter {
            List<SerTransField> serTransField;

            public List<SerTransField> getSerTransField() {
                return serTransField;
            }

            public void setSerTransField(List<SerTransField> serTransField) {
                this.serTransField = serTransField;
            }

            public HealthValueAdapter() {
            }

            HealthValueAdapter(List<SerTransField> serTransField) {
                this.serTransField = serTransField;
            }

            @Override
            public int getCount() {
                if (serTransField == null || serTransField.size() == 0) {
                    return 0;
                }
                return serTransField.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                if (convertView == null) {
                    ViewHolder h1 = new ViewHolder();
                    convertView = LayoutInflater.from(context).inflate(
                            R.layout.additem, null);
                    h1.te_name = (TextView) convertView
                            .findViewById(R.id.textname);
                    h1.te_values = (EditText) convertView
                            .findViewById(R.id.et_values);
                    h1.unitName = (TextView) convertView
                            .findViewById(R.id.unitName);
                    convertView.setTag(h1);
                }
                final ViewHolder h = (ViewHolder) convertView.getTag();
                SerTransField serTranValue = serTransField.get(position);
                h.te_name.setText(serTranValue.getFieldName());
                h.te_values.setText(serTranValue.getFieldValue() == null ? ""
                        : serTranValue.getFieldValue());
                h.te_values.setTag(serTranValue);
                h.unitName.setText(serTranValue.getFieldUnit());
                return convertView;
            }
        }
    }

    private void uploadReSendValue(long serTransId, String transStatus, final int position) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("serTransId", serTransId);
        json.put("transStatus", transStatus);
        json.put("waitersId", userId);
        json.put("waitersName", userNameStr);
        json.put("isHasField", 1);
        JSONArray jsArray = new JSONArray();
        json.put("fieldList", jsArray);
        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject fieldJson = new JSONObject();
            fieldJson.put("serTransFieldId", fieldList.get(i)
                    .getSerTransFieldId());
            fieldJson.put("fieldValue", fieldList.get(i).getFieldValue());
            jsArray.put(fieldJson);
        }
        if (transStatus.equals("4") || transStatus.equals("5")
                || transStatus.equals("6") || transStatus.equals("10")) {
            json.put("supplierName", supplierName);
        }
        json.put("serSignRecordId", SharedPreferenceUtil.getUserInfo(
                Constants.UserInfo.SER_SIGNRECORD_ID, getApplicationContext()));
        LRequest lRequest = new LRequest();
        try {
            lRequest.addParam("updateAppointmentStatusForApp", URLEncoder.encode(json.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        lRequest.setUri(ServerPort.UPDATE_AUTOMA_TASK_JSON);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    Log.d(TAG, "responseBean==" + responseBean);
                    if (listData != null && "200".equals(code) && adapter != null) {
                        listData.remove(position);
                        adapter.notifyDataSetChanged();
                    }
//                    try {
//                        getServerTask(userId,signCustomerId);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });

    }

    private void uploadReSend(long serTransId, String transStatus, final int position) throws JSONException {
        try {
            JSONObject json = new JSONObject();
            json.put("serTransId", serTransId);
            json.put("transStatus", transStatus);
            json.put("waitersId", userId);
            json.put("waitersName", userNameStr);
            json.put("isHasField", 0);
            if (transStatus.equals(4) || transStatus.equals(5)
                    || transStatus.equals(6) || transStatus.equals(10)) {
                json.put("supplierName", SharedPreferenceUtil.getUserInfo("supplierName",
                        getApplicationContext()));
            }
            json.put("serSignRecordId", SharedPreferenceUtil.getUserInfo(
                    Constants.UserInfo.SER_SIGNRECORD_ID, getApplicationContext()));
            Log.d(TAG, "json.toString()==" + json.toString());
            LRequest lRequest = new LRequest();
            lRequest.addParam("token", token);
            lRequest.addParam("updateAppointmentStatusForApp", URLEncoder.encode(json.toString(), "UTF-8"));
            lRequest.setUri(ServerPort.UPDATE_AUTOMA_TASK_JSON);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null) {
                        Log.d(TAG, "responseBean==" + responseBean);
                        if (listData != null && "200".equals(code) && adapter != null) {
                            listData.remove(position);
                            adapter.notifyDataSetChanged();
                        }
//                    try {
//                        getServerTask(userId,signCustomerId);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                    }
                }
            });

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void showProgress() {
        try {
            showProgress(HealthTaskActivity.this);
        } catch (Exception e) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception e) {

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.activity_health_task;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }


}
